package com.wx.tgp.shopping.service.impl;

import com.wx.tgp.shopping.entity.Category;
import com.wx.tgp.shopping.service.CategoryService;
import com.wx.tgp.shopping.util.HibernateSessionFactory;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 * Created by Administrator on 2016/5/26.
 */
public class CategoryServiceImpl implements CategoryService {

    /**
     * 用来测试hibernate环境是否正常
     * @param category
     */
    @Override
    public void save(Category category) {
        // 通过工厂来获取到Session
        Session session = HibernateSessionFactory.getSession();
        try {
            session.getTransaction().begin();
            session.save(category);
            session.getTransaction().commit();
        } catch (Exception e){
            session.getTransaction().rollback();
            throw  new RuntimeException();
        } finally {
            HibernateSessionFactory.closeSession();;
        }
    }

    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory){
        this.sessionFactory = sessionFactory;
    }

    public Session getSession(){
       return sessionFactory.getCurrentSession();
    }

    public void update(Category category){
        getSession().save(category);
    }
}
